package utils;

import java.lang.reflect.*;
import java.util.*;

import controllers.*;

import dto.http.*;


import play.api.mvc.Call;
import play.libs.F.Function;
import play.libs.F.Promise;
import play.libs.*;
import play.mvc.Http.*;

public class HttpUtils {

	public enum HttpMethods{
		GET,
		POST,
		PUT,
		DELETE
	}
	
	//Call API
	//needs Play env
	public static String callUrlSync(String url, String method, Map<String, String> params){
		Promise<WS.Response> callResult = null;
		play.libs.WS.WSRequestHolder requestHolder = WS.url(url);
		for(String crtParamKey: params.keySet()){
			requestHolder.setQueryParameter(crtParamKey, params.get(crtParamKey));
		}
		
		if(method.equals(HttpMethods.POST.name())){
			callResult = requestHolder.post(new String());
		}else if(method.equals(HttpMethods.PUT.name())){
			callResult = requestHolder.put(new String());
		}else if(method.equals(HttpMethods.DELETE.name())){
			callResult = requestHolder.delete();
		}else{
			callResult = requestHolder.get();
		}
		
		Promise<String> resultParams = callResult.map(
				new Function<WS.Response, String>(){
					public String apply(WS.Response response){
						return response.getBody();
					}
				}
		);
		return resultParams.get();
	}
	
	//redirect to one Play 2.0 controller
	//routes.UserAuthController.login().url()
	public static String routeContextPath = "controllers.routes";
	public static String controllerContext = "controllers.Reverse";
	public static String getPlayUrlWithControllerName(
			String controller,
			String method) throws Exception{
		Object controllerReversedObj = AniReflectUtils.getStaticField(routeContextPath, controller);
		
		Call retController = 
				(Call)AniReflectUtils.callMethod(controllerReversedObj, controllerContext + controller, method);
		
		return retController.url();
    }
}
